package com.milo.common.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 * @author Milo Lee
 * @date 2021-12-02 16:55
 *
 */
public class JwtUtils {

    final static String JWT_KEY = "1cabffaa2dd04854b4495109d696d0e2";

     /**
     * 生成jwt
     * 使用Hs256算法, 私匙使用固定JWT_SEC秘钥
     * @param data  用户信息
     * @return
     */
    public static String createJWT(String secret,long expTime, JSONObject data) {
        // 生成密钥
        Key key = new SecretKeySpec(secret.getBytes(),
                SignatureAlgorithm.HS256.getJcaName());
        JSONObject header = new JSONObject();
        header.put("typ", "JWT");
        // 生成JWT的时间
        long nowMillis = System.currentTimeMillis();
        long exp = nowMillis + expTime;//过期时间为1分钟
        String token = Jwts.builder()
                .setHeader(header)
                .setClaims(data)
                .signWith(key, SignatureAlgorithm.HS256)
                .setExpiration(new Date(exp))//设置过期时间
                .compact(); //过期时间
        return token;
    }

    /**
     * Token的解密
     *
     * @param token  加密后的token
     * @return
     */
    public static JSONObject parseJWT(String secret, String token) {
        JSONObject result = new JSONObject();
        try {
            // 生成密钥
            Key key = new SecretKeySpec(secret.getBytes(), SignatureAlgorithm.HS256.getJcaName());
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            result.put("code", 200);
            result.put("msg", "校验成功");
            result.put("content", body);
        }catch (ExpiredJwtException mce) {
            result.put("code", -1001);
            result.put("msg", "密钥已过期");
            result.put("content", "");
        }catch (JwtException jwte) {
            result.put("code", -1002);
            result.put("msg", "token解析失败");
            result.put("content", "");
        }
        return result;
    }


    public static void main(String[] args) {
        // 生成jwt
        JSONObject map = new JSONObject();
        map.put("username","admin");
        map.put("user_id","1234");
        String jwt = JwtUtils.createJWT(JWT_KEY,60*1000,map); 
        System.out.println(jwt); // 生成token
        Map<String, Object> res = parseJWT(JWT_KEY,jwt);
        System.out.println(res);
    }
}
